/**
 * Copyright (C) 2018-2020
 * All rights reserved, Designed By www.yixiang.co
 * 注意：
 * 本软件为www.yixiang.co开发研制，未经购买不得使用
 * 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 * 一经发现盗用、分享等行为，将追究法律责任，后果自负
 */
package co.yixiang.modules.activity.rest;

import cn.binarywang.wx.miniapp.api.WxMaQrcodeService;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaCodeLineColor;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import co.yixiang.api.ApiResult;
import co.yixiang.api.YshopException;
import co.yixiang.constant.ShopConstants;
import co.yixiang.enums.AppFromEnum;
import co.yixiang.logging.aop.log.AppLog;
import co.yixiang.common.bean.LocalUser;
import co.yixiang.common.interceptor.AuthCheck;
import co.yixiang.constant.SystemConfigConstants;
import co.yixiang.modules.activity.domain.YxStoreCombination;
import co.yixiang.modules.activity.param.PinkCancelParam;
import co.yixiang.modules.activity.param.PinkShareParam;
import co.yixiang.modules.activity.service.YxStoreCombinationService;
import co.yixiang.modules.activity.service.YxStorePinkService;
import co.yixiang.modules.activity.vo.CombinationQueryVo;
import co.yixiang.modules.activity.vo.PinkInfoVo;
import co.yixiang.modules.activity.vo.StoreCombinationVo;
import co.yixiang.modules.activity.vo.YxStoreCombinationQueryVo;
import co.yixiang.modules.mp.config.WxMaConfiguration;
import co.yixiang.modules.order.service.YxStoreOrderCartInfoService;
import co.yixiang.modules.product.domain.YxStoreProduct;
import co.yixiang.modules.product.service.YxStoreProductRelationService;
import co.yixiang.modules.product.service.YxStoreProductService;
import co.yixiang.modules.services.CreatShareProductService;
import co.yixiang.modules.shop.domain.YxSystemAttachment;
import co.yixiang.modules.shop.service.YxSystemAttachmentService;
import co.yixiang.modules.shop.service.YxSystemConfigService;
import co.yixiang.modules.user.domain.YxUser;
import co.yixiang.modules.user.service.YxUserBillService;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.awt.*;
import java.io.*;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 拼团前端控制器
 * </p>
 *
 * @author hupeng
 * @since 2019-11-19
 */
@Slf4j
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Api(value = "拼团", tags = "营销:拼团", description = "拼团")
public class StoreCombinationController {

    private final YxStoreCombinationService storeCombinationService;
    private final YxStorePinkService storePinkService;
    private final YxSystemConfigService systemConfigService;
    private final YxStoreProductRelationService relationService;
    private final CreatShareProductService creatShareProductService;
    private final YxUserBillService userBillService;
    private final YxStoreOrderCartInfoService orderCartInfoService;
    private final YxStoreProductService storeProductService;
    private final YxSystemAttachmentService systemAttachmentService;

    @Value("${file.path}")
    private String path;


    /**
     * 拼团产品列表
     */
    @GetMapping("/combination/list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码,默认为1", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "limit", value = "页大小,默认为10", paramType = "query", dataType = "int")
    })
    @ApiOperation(value = "拼团产品列表",notes = "拼团产品列表")
    public ApiResult<CombinationQueryVo> getList(@RequestParam(value = "page",defaultValue = "1") int page,
                                                 @RequestParam(value = "limit",defaultValue = "10") int limit){
        return ApiResult.ok(storeCombinationService.getList(page, limit));
    }

    /**
     * 拼团产品详情
     */
    @AppLog(value = "查看拼团产品详情", type = 1)
    @AuthCheck
    @GetMapping("/combination/detail/{id}")
    @ApiOperation(value = "拼团产品详情",notes = "拼团产品详情")
    public ApiResult<StoreCombinationVo> detail(@PathVariable Long id){
        if(ObjectUtil.isNull(id)) {
            throw new YshopException("参数错误");
        }
        Long uid = LocalUser.getUser().getUid();
        StoreCombinationVo storeCombinationVo = storeCombinationService.getDetail(id,uid);
        storeCombinationVo.setUserCollect(relationService
                .isProductRelation(storeCombinationVo.getStoreInfo().getProductId(),uid));
        return ApiResult.ok(storeCombinationVo);
    }

    /**
     * 拼团产品详情
     */
    @AppLog(value = "查看推三返一产品详情", type = 1)
    @AuthCheck
    @GetMapping("/combination/rebateDetail/{id}")
    @ApiOperation(value = "推三返一产品详情",notes = "推三返一产品详情")
    public ApiResult<Map<String,Object>> rebateDetail(@PathVariable Long id){
        if(ObjectUtil.isNull(id)) {
            throw new YshopException("参数错误");
        }
        Map<String,Object> map = new LinkedHashMap<>();
        Long uid = LocalUser.getUser().getUid();
        StoreCombinationVo storeCombinationVo = storeCombinationService.getRebateDetail(id,uid);
        YxStoreCombination storeCombination = storeCombinationService.getById(id);
        /*storeCombinationVo.setUserCollect(relationService
                .isProductRelation(storeCombinationVo.getStoreInfo().getProductId(),uid));*/
        map.put("storeCombinationVo",storeCombinationVo);
        int peoper = storeCombinationVo.getStoreInfo().getPeople();
        int pinkOkSum =storePinkService.getPinkOk4selfRebateSumTotalNum(uid,id);
        int remainder =peoper-pinkOkSum%peoper;//余数
        double totalSum =userBillService.rebateCommissionSum(uid,"13",id);//总收益
        String count =orderCartInfoService.getOrderCountByRebate4pay(uid,id,storeCombinationVo.getStoreInfo().getProductId());
        //查询用户是否购买并且已支付过推三返一的产品
        String countShare =orderCartInfoService.getOrderCountByRebate4apay(uid,id,storeCombinationVo.getStoreInfo().getProductId());
        String whether_buy ="Y";
        String whether_share ="N";
        if("0".equals(count)){
            whether_buy ="N";
        }
        if("0".equals(countShare)){
            whether_share ="Y";
        }
        map.put("whether_buy",whether_buy);
        map.put("whether_share",whether_share);
        map.put("remainder",remainder);
        map.put("totalSum",totalSum);
        map.put("selfCount",storeCombinationVo.getPinkOkList().size());
        map.put("stopTime",storeCombination.getStopTime().getTime());
        map.put("combinationType",storeCombination.getCombinationType());
        return ApiResult.ok(map);
    }

    /**
     * 拼团明细
     */
    @AppLog(value = "查看拼团明细", type = 1)
    @AuthCheck
    @GetMapping("/combination/pink/{id}")
    @ApiOperation(value = "拼团明细",notes = "拼团明细")
    public ApiResult<PinkInfoVo> pink(@PathVariable Long id){
        if(ObjectUtil.isNull(id)) {
            throw new YshopException("参数错误");
        }
        Long uid = LocalUser.getUser().getUid();
        return ApiResult.ok(storePinkService.pinkInfo(id,uid));
    }

    /**
     * 拼团海报
     */
    @AppLog(value = "生成拼团海报", type = 1)
    @AuthCheck
    @PostMapping("/combination/poster")
    @ApiOperation(value = "拼团海报",notes = "拼团海报")
    public ApiResult<Object> poster(@Validated @RequestBody PinkShareParam param){
        String siteUrl = systemConfigService.getData(SystemConfigConstants.SITE_URL);
        if(StrUtil.isEmpty(siteUrl)){
            throw new YshopException("未配置h5地址");
        }
        String apiUrl = systemConfigService.getData(SystemConfigConstants.API_URL);
        if(StrUtil.isEmpty(apiUrl)){
            throw new YshopException("未配置api地址");
        }
        YxUser userInfo = LocalUser.getUser();
        Map<String,Object> map = Maps.newHashMap();
        String spreadUrl = creatShareProductService.getPinkPosterUrl(Long.valueOf(param.getId()),userInfo,
                siteUrl,apiUrl,path,param.getFrom());
        map.put("url",spreadUrl);
        return ApiResult.ok(map);
    }

    /**
     * 推三返一海报
     */
    @AppLog(value = "生成推三返一海报", type = 1)
    @AuthCheck
    @PostMapping("/combination/rebate")
    @ApiOperation(value = "推三返一海报",notes = "推三返一海报")
    public ApiResult<Object> rebate(@Validated @RequestBody PinkShareParam param) throws IOException, FontFormatException {
        String siteUrl = systemConfigService.getData(SystemConfigConstants.SITE_URL);
        if(StrUtil.isEmpty(siteUrl)){
            throw new YshopException("未配置h5地址");
        }
        String apiUrl = systemConfigService.getData(SystemConfigConstants.API_URL);
        if(StrUtil.isEmpty(apiUrl)){
            throw new YshopException("未配置api地址");
        }
        YxUser userInfo = LocalUser.getUser();
        Long combinationId =Long.valueOf(param.getId());
        YxStoreCombination storeCombination = storeCombinationService.getById(combinationId);
        if(ObjectUtil.isNull(storeCombination)) {
            throw new YshopException("拼团产品不存在");
        }
        String from =param.getFrom();
        YxStoreProduct productDTO = storeProductService.getById(storeCombination.getProductId());
        String name = combinationId+"_"+userInfo.getUid() + "_"+from+"_pink_share_wap.jpg";
        YxSystemAttachment attachment = systemAttachmentService.getInfo(name);
        String fileDir = path+"qrcode"+ File.separator;
        String qrcodeUrl = "";
        String str ="id="+combinationId+"-spread="+userInfo.getUid()+"-pageType=good";
        String url ="pages/activity/RebateDetails/index";
        String spreadUrl = "";
        if(ObjectUtil.isNull(attachment)){
            //生成二维码
            File file = FileUtil.mkdir(new File(fileDir));
            if(AppFromEnum.ROUNTINE.getValue().equals(from)){
                /*siteUrl = siteUrl+"/pink/";
                QrCodeUtil.generate(siteUrl+"?pinkId="+pinkId+"&spread="+uid+"&pageType=group&codeType="+AppFromEnum.ROUNTINE.getValue(), 180, 180,
                        FileUtil.file(fileDir+name));*/
                getminiqrQr(str,fileDir,name,url);
            }
            else if(AppFromEnum.APP.getValue().equals(from)){
                siteUrl = siteUrl+"/pink/";
                QrCodeUtil.generate(siteUrl+"?id="+combinationId+"&spread="+userInfo.getUid()+"&pageType=group&codeType="+AppFromEnum.ROUNTINE.getValue(), 180, 180,
                        FileUtil.file(fileDir+name));
            }
            else if(AppFromEnum.H5.getValue().equals(from)){
                QrCodeUtil.generate(siteUrl+"/activity/group_rule/"+combinationId+"?spread="+userInfo.getUid(), 180, 180,
                        FileUtil.file(fileDir+name));
            }else {
                String uniUrl = systemConfigService.getData(SystemConfigConstants.UNI_SITE_URL);
                siteUrl =  StrUtil.isNotBlank(uniUrl) ? uniUrl :  ShopConstants.DEFAULT_UNI_H5_URL;
                QrCodeUtil.generate(siteUrl+"/"+url+"?id="+combinationId+"&spread="+userInfo.getUid(), 180, 180,
                        FileUtil.file(fileDir+name));
            }


            systemAttachmentService.newAttachment4SpreadAdd(name,String.valueOf(FileUtil.size(file)),
                    fileDir+name,"qrcode/"+name,userInfo.getUid(),"","3",combinationId);

            qrcodeUrl = apiUrl + "/api/file/qrcode/"+name;
        }else{
            qrcodeUrl = apiUrl + "/api/file/" + attachment.getSattDir();
        }
        String spreadPicName = combinationId+"_"+userInfo.getUid() + "_"+from+"_pink_user_spread.jpg";
        String spreadPicPath = fileDir+spreadPicName;

        YxSystemAttachment attachmentT = systemAttachmentService.getInfo(spreadPicName);
        String rr = creatShareProductService.getPinkRebateUrl(productDTO,qrcodeUrl,
                spreadPicName,spreadPicPath,apiUrl,userInfo,combinationId,storeCombination.getImage());
        return ApiResult.ok(rr);
    }

    /**
     * 取消开团
     */
    @AppLog(value = "取消开团", type = 1)
    @AuthCheck
    @PostMapping("/combination/remove")
    @ApiOperation(value = "取消开团",notes = "取消开团")
    public ApiResult<Boolean> remove(@Validated @RequestBody PinkCancelParam param){
        Long pinkId = Long.valueOf(param.getId());
        Long cId = Long.valueOf(param.getCid());
        Long uid = LocalUser.getUser().getUid();
        storePinkService.removePink(uid,cId,pinkId);
        return ApiResult.ok();
    }


    public void getminiqrQr(String sceneStr,String path,String name,String url) {
        OutputStream outputStream = null;
        InputStream inputStream = null;
        try {
            WxMaService wxMaService = WxMaConfiguration.getWxMaService();
            WxMaQrcodeService wxMaQrcodeService = wxMaService.getQrcodeService();
            File file = new File(path+name);
            if (!file.exists()){
                file.createNewFile();
            }
            outputStream = new FileOutputStream(file);
            WxMaCodeLineColor line_color = new WxMaCodeLineColor("0","0","0");
            byte[] qrCodeBytes = wxMaQrcodeService.createWxaCodeUnlimitBytes(sceneStr, url, 130, false, line_color, true);
            inputStream = new ByteArrayInputStream(qrCodeBytes);
            int len = 0;
            while ((len = inputStream.read(qrCodeBytes, 0, 1024)) != -1) {
                outputStream.write(qrCodeBytes, 0, len);
            }
            outputStream.flush();
        } catch (Exception ex) {
            log.info("生成小程序码失败，message:{}", ex.getMessage());
        } finally {
            try {
                outputStream.close();
            } catch (Exception ex) {
                log.error("关闭IO流失败,msg:{}", ex.getMessage());
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

